/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package herramientas;


import java.io.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
 *
 * @author Usuario
 */
public class DescargaAction extends org.apache.struts.action.Action {



    /*
     * forward name="success" path=""
     */
    private static final String SUCCESS = "success";
    private final static String FAILURE = "failure";
    private final static String INVALIDU = "invalidU";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        DescargaForm formBean = (DescargaForm) form;        
        baseDatos bd = baseDatos.getInstance();
       String filePath = bd.ArchivoGetRuta(formBean.getIdA());       
           response.setContentType("application/octet-stream");           
            FileInputStream fileToDownload = new FileInputStream(filePath);
        ServletOutputStream output = response.getOutputStream();
        String nombreArchivo = filePath.substring(filePath.lastIndexOf("\\")+1
                                , filePath.length());
        response.setHeader("Content-Disposition", "attachment; filename="
                + nombreArchivo);

        ByteArrayOutputStream output1 = new ByteArrayOutputStream(); 
        int readBytes = 0;
        byte[] buffer = new byte[10000];
        while ((readBytes = fileToDownload.read(buffer, 0, 10000)) != -1) {
            output.write(buffer, 0, readBytes);
            output1.write(buffer, 0, readBytes);
        }

        output.flush();
        output.close();
        fileToDownload.close();
        String mensajeId = formBean.getIdM();
        String mensajeIdS = formBean.getIdMS();
        if (mensajeId.equals("")){
            request.setAttribute("idS", mensajeIdS);   
        }
        else{
            request.setAttribute("id", mensajeId);   
        }
        return mapping.findForward(SUCCESS); 
   }
}
